<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
	<th:block th:fragment="fileListDiv">
		<div class="row isShow">
			<div class="col-md-12">
				<div class="portlet light bordered">
					<div class="portlet-title content-title">
						<span class="content-title-text" id="fileList-title">附件上传</span>
						<div class="tools">
							<a href="javascript:;" class="collapse" data-original-title="" title=""></a>
						</div>

						<div class="actions">
							<a class="btn blue isShow" href="javascript:void(0);" th:if="${false == readonly}"
							   onclick="fileList.fileUpload()">添加</a>
							<input type="file" id="file_control" style="display: none;" multiple='multiple' />
						</div>
					</div>
					<div class="portlet-body content-body">
						<table id="file_table" class="easyui-datagrid" style="width: 100%"></table>
					</div>
				</div>
			</div>
		</div>
	</th:block>
	<th:block th:fragment="fileListScripts">
		<script th:inline="javascript">
			var fileList = {
				progress:{},//文件上传进度信息
				addUrl: '/form/file/add',
				delUrl: '/form/file/delete',
				listAllUrl: '/form/file/listAll',
				modelName: 'common',
				params:{},
				index: 0,
				modelId: '',
				isSubmit: true,
				isCheckMainDataId: false,  //上传附件时是否需要检查主表是否已经保存。true-需要检查，false-不检查
				acceptFileTypes: '',//上传附件类型
				init: function (options) {
					this.setOptions(options);
					//初始化文件上传
					this.initFileContrl();
					this.initFilesTable();
				},
				setOptions: function(options){
					if(options.addUrl) this.addUrl = options.addUrl;
					if(options.isCheckMainDataId) this.isCheckMainDataId = options.isCheckMainDataId;
					if(options.delUrl) this.delUrl = options.delUrl;
					if(options.listAllUrl) this.listAllUrl = options.listAllUrl;
					if(options.acceptFileTypes) this.acceptFileTypes = options.acceptFileTypes;
					if(options.modelName) this.modelName = options.modelName;
					if(options.params) this.params = options.params;
					if(options.modelId) this.modelId = options.modelId;
					if(options.isSubmit !== undefined) this.isSubmit = options.isSubmit;
					if(options.title) $("#fileList-title").val(options.title);
				},
				//附件上传控件初始化
				initFileContrl: function(){
					$((this.modelId ? "#" + this.modelId + " ": '') + "#file_control").change(function () {
						if($(this).val() != ''){
							var files = $(this)[0].files;
							for(var i = 0;i < files.length; i++) {
								fileList.uploadFile(files[i]);
							}
							$(this).val('');
						}
					})
				},
				uploadFile: function(file){
					if (this.acceptFileTypes) {
						var fileTypes = '',
								acceptFileTypes = undefined;
						if (typeof this.acceptFileTypes == 'string') {
							var types = this.acceptFileTypes.split(",");
							for (var i = 0; i < types.length; i++) {
								if (fileTypes) {
									fileTypes += "|";
								}
								fileTypes += types[i].toLowerCase();
							}
							if (fileTypes) {
								fileTypes = "/(\\.|\\/)(" + fileTypes + ")$/i";
								acceptFileTypes = eval('(' + fileTypes + ')');
							}
						} else {
							toastr["error"]("上传文件类型格式不正确！", "提示!", function () {});
							return;
						}
						if (!acceptFileTypes.test(file.name.toLowerCase())) {
							toastr["error"]("上传文件类型不正确！", "提示!", function () {});
							return;
						}
					}
					fileList.index++;
					var item = {
						mainId: $("#mid").val(),
						fileName: file.name,
						progress: 0,
						progressId: fileList.index,
					};
					fileList.progress[item.progressId] = {
						progress: 0,
						start: false,
						ajax: null
					};
					$((this.modelId ? '#' + this.modelId + ' ': '') + "#file_table").datagrid("appendRow",item);
					$((this.modelId ? '#' + this.modelId + ' ': '') + '#progress' + item.progressId).progressbar({
						value: 0
					});

					var formData = new FormData();
					formData.append("modelName", fileList.modelName);
					formData.append("files[]", file);
					var parameterName = /*[[${_csrf.headerName}]]*/ '',
							_csrf = {};
					_csrf[parameterName] = /*[[${_csrf.token}]]*/ '';
					fileList.progress[item.progressId].ajax = $.ajax({
						url: "/filestore/item/save",
						type: "post",
						dataType: "json",
						data: formData,
						headers: _csrf,
						processData: false, // ⑧告诉jQuery不要去处理发送的数据
						contentType: false, // ⑨告诉jQuery不要去设置Content-Type请求头
						xhr: function() {
							var xhr = new XMLHttpRequest();
							//使用XMLHttpRequest.upload监听上传过程，注册progress事件，打印回调函数中的event事件
							xhr.upload.addEventListener('progress', function (e) {
								//loaded代表上传了多少
								//total代表总数为多少
								var progressRate = parseInt((e.loaded / e.total) * 10000) / 100;
								if(progressRate > 80) progressRate = 80;
								fileList.progress[item.progressId].progress = progressRate;
								if(!fileList.progress[item.progressId].start) fileList.startProgress(item.progressId,item);
							});

							return xhr;
						},
						success: function (result) {
							if (result.success && result.obj.length > 0) {
								var obj = result.obj[0];
								delete obj["@type"];
								delete obj["fileStoreNode"];
								fileList.progress[item.progressId].ajax = null;
								fileList.progress[item.progressId].progress = fileList.isSubmit ? 90 : 100;
								if(!fileList.isSubmit) {
									obj.fileId = obj.mid;
									delete obj.mid;
									$.extend(item,this.params,obj);
								}
								if(!fileList.progress[item.progressId].start) fileList.startProgress(item.progressId,item);
								if(fileList.isSubmit) fileList.setFromFile(item,obj);
							} else {
								fileList.setProgress(-1,item);
							}
						},
						error: function (msg) {
							fileList.setProgress(-1,item);
						}
					});
				},
				setFromFile: function(item,obj){
					obj.fileId = obj.mid;
					delete obj.mid;
					$.extend(obj,this.params);
					if(App._csrf){
						$.extend(obj,App._csrf);
					}
					fileList.progress[item.progressId].ajax = $.ajax({
						type: "post",
						dataType: "json",
						url: this.addUrl,
						data: obj,
						cache: false,
						processData: true,
						contentType: 'application/x-www-form-urlencoded',
						success: function (result) {
							if (result && result.success === false) {
								fileList.setProgress(-1,item);
							} else {
								$.extend(item,result.obj);
								fileList.progress[item.progressId].ajax = null;
								fileList.progress[item.progressId].progress = 100;
								if(!fileList.progress[item.progressId].start) fileList.startProgress(item.progressId,item);
							}
						},
						error: function (jqXHR, textStatus, errorThrown) {
							console.log(jqXHR.responseText);
							fileList.setProgress(-1,item);
						}
					});
				},
				//设置进度条动态滚动
				startProgress: function(progressId,item){
					var bar = $((this.modelId ? '#' + this.modelId + ' ': '') + '#progress' + progressId);
					if(!(bar.length && bar.data("progressbar"))) {
						fileList.startProgress(progressId,item);
						return
					}
					var value = bar.progressbar('getValue');
					if (value < this.progress[progressId].progress){
						this.progress[progressId].start = true;
						value += Math.floor(Math.random() * 10);
						if (value > this.progress[progressId].progress) value = this.progress[progressId].progress;
						value = Math.floor(value);
						bar.progressbar('setValue', value);
						var timeout = setTimeout(function () {
							fileList.startProgress(progressId,item);
							clearTimeout(timeout);
						}, 100);
					} else if(value == 100){
						this.setProgress(100,item);
					} else {
						this.progress[progressId].start = false;
					}
				},
				//设置列表中的值
				setProgress: function(progress,data){
					var list = $((this.modelId ? '#' + this.modelId + ' ': '') + "#file_table").datagrid("getData");
					for (var i = 0; i < list.rows.length; i++){
						var item = list.rows[i];
						if(data.progressId == item.progressId){
							$((this.modelId ? '#' + this.modelId + ' ': '') + "#file_table").datagrid("updateRow",{
								index: i,
								row: {
									progress: progress
								}
							});
							if(progress == -1) progress = 0;
							$((this.modelId ? '#' + this.modelId + ' ': '') + '#progress' + item.progressId).progressbar({
								value: progress
							});
							return;
						}
					}
				},
				//附件上传列表初始化
				initFilesTable:function() {
					$((this.modelId ? '#' + this.modelId + ' ': '') + "#file_table").datagrid({
						height: 'auto',
						width: '100%',
						// todo: 需要参数化
						url: this.listAllUrl,
						// todo: 需要参数化
						queryParams: this.params,
						fitColumns: true,
						columns: [
							[
								{
									field: 'number',title: '序号',align: "center",fixed: true,formatter: function (data, row, index) {
										return index + 1;
									}
								},
								{
									field: 'fileName',title: '文件名',align: "left",fixed: false,width: 350,formatter: App.publicBubble
								},
								{
									field: 'progress',title: '上传进度',align: "left",fixed: true,width: 250,formatter: function (data, row, index) {
										var showText = '',progressId = row.progressId;
										var className = 'progress-panel';
										if(progressId == undefined){
											data = 100;
											progressId = index + 1;
											row.progressId = progressId;
										}
										if(data == 100){
											className += " success";
											showText += "上传成功";
										} else if(data == -1) {
											className += " fail";
											showText += '<i class="fileUpload"></i>';
										} else {
											showText += "正在上传";
										}
										var html = '<div class="' + className + '"><div id="progress' + progressId + '" class="file-progress-input"></div></div>' + showText;
										return html;
									}
								},
								{
									field: 'creator',title: '上传人',align: "left",fixed: false,width: 125,formatter: App.publicBubble
								},
								{
									field: 'createTime',title: '上传时间',align: "left",fixed: false,width: 125,formatter: function (data, row, index) {
										if (data == undefined) {
											return '<div title=""></div>'
										} else {
											var valueDate = data.slice(0, 10)
											return '<div title="' + valueDate + '">' + valueDate + '</div>'
										}
									}
								},
								{
									field: 'action',title: '操作',fixed: true,width: '250px', align: "left",formatter: function (data, row, index) {
										var actions = "";
										if(row.progress == 100 || row.progress === undefined){
											actions += "<a onclick='App.downLoadFile(\"" + row.htmlUrl + "\",\"" + row.fileName + "\")' style='color: #2D99FE;margin-right: 8px'>下载附件</a>";
										}
										/*[+ [#th:block th:if="${false == readonly}"] +]*/
										actions += "<a href='javascript:void(0);' onclick='fileList.deleteFile(" + row.mid + "," + row.progressId +")'>删除</a>";
										/*[+ [/th:block] +]*/
										return actions;
									}
								},
							]
						],
						method: "get",
						remoteFilter: true,
						remoteSort: true,
						clientPaging: false,
						striped: true, //表格设置为条纹
						onLoadSuccess: function (data) {
							$((this.modelId ? '#' + this.modelId + ' ': '') + '.file-progress-input').progressbar({
								value: 100
							});
							fileList.index = data.rows.length;
						},
					});
				},
				//附件上传 添加
				fileUpload: function() {
					//检查mid是否为空
					if(this.isCheckMainDataId&&(!this.params.mainDataId||this.params.mainDataId==-1)){
						$.messager.alert("提醒", "请先点击保存按钮,保存主表数据之后才能上传附件", "info");
						return
					}

					$("#file_control").click();
				},
				//附件上传 删除
				deleteFile: function (mid,progressId) {
					var progressData = {};
					$((this.modelId ? '#' + this.modelId + ' ': '') + '.file-progress-input').each(function(){
						var value = $(this).progressbar("getValue");
						var key = $(this).attr("id");
						progressData[key] = value;
					})
					var list = $((this.modelId ? '#' + this.modelId + ' ': '') + "#file_table").datagrid("getData"),index;
					for (var i = 0; i < list.rows.length; i++){
						var item = list.rows[i];
						if((mid && mid == item.mid) || (progressId && progressId == item.progressId)){
							index = $((this.modelId ? '#' + this.modelId + ' ': '') + '#file_table').datagrid('getRowIndex',item);
							break;
						}
					}
					if(mid){
						var that = this;
						$.messager.confirm("文件删除警告", "请确认是否删除文件？", function (result) {
							if (result) {
								var data = {mid: mid};
								$.extend(data,fileList.params);
								if(App._csrf){
									$.extend(data,App._csrf);
								}
								$.ajax({
									type: "post",
									dataType: "json",
									// todo: 需要参数化
									url: fileList.delUrl,
									data: data,
									cache: false,
									processData: true,
									contentType: 'application/x-www-form-urlencoded',
									success: function (result) {
										if (result && result.success === false) {
										} else {
											$((that.modelId ? '#' + that.modelId + ' ': '') + '#file_table').datagrid('deleteRow', index);
											that.resetProgressByDel(progressData);
										}
									},
									error: function (jqXHR, textStatus, errorThrown) {
										console.log(jqXHR.responseText);
									}
								});
							} else {
								result = false;
							}
							return result;
						});

					} else if(this.progress[progressId].ajax) {
						this.progress[progressId].ajax.abort();
						this.progress[progressId].ajax = null;
						$((this.modelId ? '#' + this.modelId + ' ': '') + '#file_table').datagrid('deleteRow', index);
						this.resetProgressByDel(progressData);
					} else {
						$((this.modelId ? '#' + this.modelId + ' ': '') + '#file_table').datagrid('deleteRow', index);
						this.resetProgressByDel(progressData);
					}
				},
				resetProgressByDel: function (data) {
					for (var key in data) {
						var progressbar = $((this.modelId ? '#' + this.modelId + ' ': '') + "#" + key);
						if(progressbar.length) {
							progressbar.progressbar({
								value: data[key]
							});
						}
					}
				},
				//下载
				downloadVoucherUrl: function (htmlUrl) {
					top.window.open(htmlUrl, "下载");
				},
			}
		</script>
	</th:block>

	<th:block th:fragment="processDefinitionDiv">
		<div class="row" id="taskId_div" th:if="${null != taskId && 0 == nodeType}">
			<div class="col-md-12">
				<div class="portlet light bordered">
					<div class="portlet-title content-title">
						<span class="content-title-text">审批意见</span>
						<div class="tools">
							<a href="javascript:;" class="collapse" data-original-title="" title=""></a>
						</div>
						<div class="actions">
<!--							<a class="btn blue isShow" href="javascript:void(0);" th:if="${false == readonly}"-->
<!--							   onclick="processDefinition.passApproval()">审批通过</a>-->
<!--							<a class="btn default isShow" href="javascript:void(0);" th:if="${false == readonly}"-->
<!--							   onclick="processDefinition.rejectApproval()">审批驳回</a>-->
						</div>
					</div>
					<div class="portlet-body content-body">
						<div class="m-grid">
							<div class="m-grid-row">
								<div class="m-grid-col m-grid-col-middle m-grid-col-right m-grid-col-md-1">
									<div class="form-label-wrapper">
										<span class="form-label" style="padding-top: 0">审批状态</span>
									</div>
								</div>
								<div class="m-grid-col m-grid-col-middle m-grid-col-left m-grid-col-md-11">
									<div class="form-group">
										<span><input type="radio" name="outcome" value="1" checked="checked"/>审批通过</span>
										<span style="margin-left: 30px"><input type="radio" name="outcome" value="0"/>审批驳回</span>
										<span th:if="${showTerminal}" style="margin-left: 30px"><input type="radio" name="outcome" value="-1"/>终止流程</span>
									</div>
								</div>
							</div>
						</div>
						<div class="m-grid">
							<div class="m-grid-row">
								<div class="m-grid-col m-grid-col-middle m-grid-col-right m-grid-col-md-1">
									<div class="form-label-wrapper">
										<span class="form-label" style="padding-top: 0">审批意见</span>
									</div>
								</div>
								<div class="m-grid-col m-grid-col-middle m-grid-col-left m-grid-col-md-11">
									<div class="form-group">
										<textarea id="task_comment" oninput="processDefinition.resizeTextarea(this)" onkeydown="processDefinition.resizeTextarea(this)" onkeyup="processDefinition.resizeTextarea(this)" onfocus="processDefinition.resizeTextarea(this)" onblur="processDefinition.resizeTextarea(this)" class="form-control" style="height: 100px;overflow: hidden"></textarea>
									</div>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>

		<div class="row" id="processInstanceId_div" th:if="${showTaskTable==null||showTaskTable}">
			<div class="col-md-12">
				<div class="portlet light bordered">
					<div class="portlet-title content-title">
						<span class="content-title-text">审批记录</span>
						<div class="tools">
							<a href="javascript:;" class="collapse" data-original-title="" title=""></a>
						</div>
					</div>
					<div class="portlet-body content-body">
						<table id="approval_records" class="easyui-datagrid" style="width: 100%"></table>
					</div>
				</div>
			</div>
		</div>
	</th:block>
	<th:block th:fragment="processDefinitionScripts">

		<script th:inline="javascript">
			var processDefinition = {
				completeTaskUrl: '',
				params:{},
				init: function (options) {

					this.setOptions(options);

					if(!$("#processInstanceId").val()){
						$("#processInstanceId_div").hide();
					} else {
						//审批历史信息
						this.approvalRecordsInit();
					}
				},
				setOptions: function(options){
					if(options.completeTaskUrl) this.completeTaskUrl = options.completeTaskUrl;
					if(options.params) this.params = options.params;
				},
				/*[+ [#th:block th:if="${null != taskId && 0 == nodeType}"] +]*/
				resizeTextarea: function(e){
					var div = document.createElement("div");
					div.style.height = '0';
					div.style.overflow = "hidden";
					div.style.lineHeight = "20px";
					var conten = document.createElement("div");
					conten.style.padding = "7px 13px";
					conten.style.wordBreak = "break-all";
					conten.innerText = $(e).val();
					div.appendChild(conten);
					$(e).parent()[0].appendChild(div);
					if($(conten).height() > 130){
						$(e).height($(conten).height() + 20);
					} else {
						$(e).height(150);
					}
					$(div).remove();
				},//
				//审批意见 审批通过
				passApproval:function() {
					this.saveApproval(1);
				},
				//审批意见 审批驳回
				rejectApproval:function() {
					this.saveApproval(0);
				},
				getVaule: function(params){
					params.comment = $("#task_comment").val();
					params.outcome = $("[name='outcome']:checked").val();
					console.log(params.outcome)
					return true;
				},
				saveApproval: function(isPass){
					var data = {
						outcome: isPass,
						comment: $("#task_comment").val(),
						taskId: /*[[${taskId}]]*/ '',
						mid: $("#mid").val(),
					};
					$.extend(data,this.params);
					if(App._csrf){
						$.extend(data,App._csrf);
					}
					App.post(this.completeTaskUrl,data,function (result) {
						if(result && result.success){
							toastr["success"](result.msg, "审批提交成功!", function () {
							});
							if(formDataObj.back){
								formDataObj.back();
							} else {
								$("#taskId_div").hide();
								$("#approval_records").datagrid("reload");
							}
						} else {
							$.messager.alert("审批提交失败！", "", "error");
						}
					},function (error) {
						$.messager.alert("审批提交失败！", "", "error");
					})
				},
				/*[+ [/th:block] +]*/
				//审批记录 列表初始化
				approvalRecordsInit:function() {
					this.params.processInstanceId = $("#processInstanceId").val();
					$("#approval_records").datagrid({
						height: 'auto',
						width: '100%',
						url: '/bpm/bpe/task/historyList',
						queryParams: this.params,
						fitColumns: true,
						columns: [
							[
								{
									field: 'number',title: '序号',align: "center",fixed: true,formatter: function (data, row, index) {
										return index + 1;
									}
								},
								/*[+ [#th:block th:if="${null != formDefine}"] +]*/
								{
									field: 'name',title: '流程节点',align: "left", width: 120, formatter: function (data, row, index) {
										return "<a href='javascript:void(0);' onclick='processDefinition.showData(" + row.taskId + ",\"" + data + "\")'>" + data + "</a>";
									}
								},
								/*[+ [/th:block] +]*/
								/*[+ [#th:block th:if="${null == formDefine}"] +]*/
								{
									field: 'name',title: '流程节点',align: "left",fixed: true,width: 120,formatter: App.publicBubble
								},
								/*[+ [/th:block] +]*/
								{
									field: 'startTime',title: '任务创建时间',align: "left",fixed: true,width: 150,formatter: App.publicBubble
								},
								{
									field: 'outcome',title: '处理结果',align: "left",fixed: true,width: 120,
									formatter: function (data, row, index) {
										return Dic.showName([[${#dic.listAll('wf.approve.outcome')}]], data);
									}
								},
								{
									field: 'assigneeName',title: '处理人',align: "left",fixed: true,width: 125,formatter: App.publicBubble
								},
								{
									field: 'endTime',title: '处理时间',align: "left",fixed: true,width: 150,formatter: App.publicBubble
								},
								{
									field: 'comment',title: '处理意见',align: "left",width: 250,formatter: App.publicBubble
								},
							]
						],
						method: "get",
						remoteFilter: false,
						remoteSort: false,
						clientPaging: false,
						emptyMsg: "表中数据为空",
						pagination: false,//分页
						pagePosition: "bottom",
						pageList: [20, 50, 100],
						pageSize: 20,
					})
				},
				/*[+ [#th:block th:if="${null != formDefine}"] +]*/
				showData: function (taskId, taskName) {
					top.window.test.implementRefresh("/form/data/" + [[${formDefine.mid}]] + "/record?taskId=" + taskId, [[${formDefine.formName}]] + "#" + taskName);
				}
				/*[+ [/th:block] +]*/
			}
		</script>
	</th:block>
</html>